package com.ccut.xunfeiSpringboot.service;/*
 * ClassName: DocumentProcessService
 * Package: com.ccut.xunfeiSpringboot.service
 * Description:
 * @Author 刘千湫
 * @Create 2025/6/2 22:12
 * @Version 1.0
 */

import com.ccut.xunfeiSpringboot.common.AjaxResult;
import com.ccut.xunfeiSpringboot.dto.StudentResumeDTO;
import com.ccut.xunfeiSpringboot.entity.School;
import com.ccut.xunfeiSpringboot.entity.Student;
import com.ccut.xunfeiSpringboot.mapper.SchoolMapper;
import com.ccut.xunfeiSpringboot.mapper.StudentMapper;
import com.ccut.xunfeiSpringboot.utils.DtoToMapConverter;
import com.ccut.xunfeiSpringboot.utils.JwtUtils;
import com.ccut.xunfeiSpringboot.utils.WordParserUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Service
public class DocumentProcessService {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private WordParserUtils wordParser;
    @Autowired
    private SchoolMapper schoolMapper;
    @Autowired
    private StudentMapper studentMapper;
    public Map<String, String> parseStudentDocument(InputStream inputStream) throws Exception {
        Map<String, String> result = new HashMap<>();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 假设每行格式为 key=value
                String[] parts = line.split("=", 2);
                if (parts.length == 2) {
                    result.put(parts[0].trim(), parts[1].trim());
                }
            }
        } catch (IOException e) {
            throw new Exception("读取输入流时发生错误", e);
        }

        return result;
    }

    public void processStudentDocument(MultipartFile file) throws Exception {


        // 提取数据中的 Map 部分用于响应
        AjaxResult result = wordParser.parseStudentDoc(file.getInputStream());

        StudentResumeDTO dto = (StudentResumeDTO) result.get("data");
        Map<String, String> data = DtoToMapConverter.convertStudent(dto);

        // 获取当前用户 ID
        Integer userId = getCurrentUserId();

        // 查询原记录
        Student existingStudent = studentMapper.selectById(userId);
        if (existingStudent == null) {
            throw new RuntimeException("用户不存在");
        }
       existingStudent.setPassword(existingStudent.getPassword());
        existingStudent.setUsername(existingStudent.getUsername());
        if (data.containsKey("密码")) existingStudent.setPassword(data.get("密码"));
        if (data.containsKey("用户名")) existingStudent.setUsername(data.get("用户名"));
        // 只更新 Word 中提供的字段
        if (data.containsKey("姓名")) existingStudent.setName(data.get("姓名"));
        if (data.containsKey("性别")) existingStudent.setSex(data.get("性别"));
        if (data.containsKey("邮箱")) existingStudent.setEmail(data.get("邮箱"));
        if (data.containsKey("电话")) existingStudent.setTelephone(data.get("电话"));
        if (data.containsKey("教育背景")) existingStudent.setEducationBackground(data.get("教育背景"));
        if (data.containsKey("技能特长")) existingStudent.setSkills(data.get("技能特长"));
        if (data.containsKey("实习经历")) existingStudent.setInternshipExperience(data.get("实习经历"));
        if (data.containsKey("校园经历")) existingStudent.setCampusExperience(data.get("校园经历"));
        if (data.containsKey("科技竞赛")) existingStudent.setTechCompetition(data.get("科技竞赛"));
        if (data.containsKey("自我评价")) existingStudent.setSelfEvaluation(data.get("自我评价"));
        // 学历字段处理
        if(data.containsKey("学历")) {
            String recordStr = data.getOrDefault("学历",
                    data.getOrDefault("学位",
                            data.getOrDefault("教育背景", null)));
            if (recordStr != null && !recordStr.trim().isEmpty()) {
                try {
                    String trimmedRecordStr = recordStr.trim();
                    Integer recordInt;

                    switch (trimmedRecordStr) {
                        case "专科":
                            recordInt = 0;
                            break;
                        case "本科":
                            recordInt = 1;
                            break;
                        case "硕士":
                            recordInt = 2;
                            break;
                        default:
                            recordInt = 3;
                            break;
                    }
                    existingStudent.setRecord(recordInt);
                } catch (Exception e) {
                    System.out.println("学历字段处理异常：" + e.getMessage());
                }
            }
        }

        System.out.println("更新");
        System.out.println("更新的学生对象：" + existingStudent);
        System.out.println("是否找到学生记录：" + (studentMapper.selectById(existingStudent.getId()) != null));

        studentMapper.updateById(existingStudent);
    }

    public void processSchoolDocument(MultipartFile file) throws Exception {
        AjaxResult result = wordParser.parseSchoolDoc(file.getInputStream());
        // 提取数据中的 Map 部分用于响应
        @SuppressWarnings("unchecked")
        Map<String, String> data = (Map<String, String>) result.get("data");

        // 获取当前用户 ID
        Integer userId = getCurrentUserId();

        // 查询原记录
        School existingSchool = schoolMapper.selectById(userId);
        if (existingSchool == null) {
            throw new RuntimeException("用户不存在");
        }
        existingSchool.setPassword(existingSchool.getPassword());
        existingSchool.setUsername(existingSchool.getUsername());
        if (data.containsKey("密码")) existingSchool.setPassword(data.get("密码"));
        if (data.containsKey("用户名")) existingSchool.setUsername(data.get("用户名"));
        if (data.containsKey("学校")) existingSchool.setSchoolName(data.get("学校"));
        if (data.containsKey("所在地") || data.containsKey("所在城市") || data.containsKey("地址")) {
            String cityRaw = data.getOrDefault("所在地",
                    data.getOrDefault("所在城市",
                            data.getOrDefault("地址", null)));
            if (cityRaw != null && !cityRaw.trim().isEmpty()) {
                // 按照逗号、中文逗号、空格等分割多个城市，并拼接为逗号分隔字符串
                String[] address = cityRaw.split("[,，\\s]+");
                existingSchool.setAddress(String.join(",", address));
            }
        }
        if (data.containsKey("联系方式")) existingSchool.setContactNumber(data.get("联系方式"));
        if (data.containsKey("校长") && !data.get("校长").trim().isEmpty()) {
            existingSchool.setPrincipal(data.get("校长").trim());
        }
        if (data.containsKey("成立时间") || data.containsKey("建校年份") || data.containsKey("创办年份")) {
            String yearStr = data.getOrDefault("成立时间",
                    data.getOrDefault("建校年份",
                            data.getOrDefault("创办年份", null)));
            if (yearStr != null && !yearStr.trim().isEmpty()) {
                try {
                    existingSchool.setEstablishedYear(Integer.parseInt(yearStr.trim()));
                } catch (NumberFormatException ignored) {
                    // 忽略非法数字
                }
            }
        }
        if (data.containsKey("学校简介")) existingSchool.setDescription("学校简介");

        System.out.println("更");
        schoolMapper.updateById(existingSchool);
    }

    public Integer getCurrentUserId() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                throw new RuntimeException("当前线程中不存在 HTTP 请求");
            }

            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("Authorization");

            if (token == null || !token.startsWith("Bearer ")) {
                throw new RuntimeException("缺少有效的 Authorization 头");
            }

            token = token.substring(7); // 去掉 "Bearer " 前缀

            // 使用你的 JwtUtils 解析 token 并获取用户 ID
            Map<String, Object> claims = jwtUtils.parseToken(token);

            Object idObj = claims.get("id");
            if (idObj == null) {
                throw new RuntimeException("Token 中未包含用户 ID");
            }

            return Integer.valueOf(idObj.toString());
        } catch (Exception e) {
            throw new RuntimeException("无法获取当前用户 ID: " + e.getMessage());
        }
    }


}